package org.lanyu.springainovel.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.lanyu.springainovel.common.config.AIModelInitService;
import org.lanyu.springainovel.chat.entity.KnowledgeBase;
import org.lanyu.springainovel.common.config.VectorStoreManager;
import org.lanyu.springainovel.common.entity.User;
import org.lanyu.springainovel.chat.mapper.KnowledgeBaseMapper;
import org.lanyu.springainovel.chat.service.KnowledgeBaseService;
import org.lanyu.springainovel.common.service.UserService;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 知识库服务实现类
 */
@Service
public class KnowledgeBaseServiceImpl implements KnowledgeBaseService {

    @Autowired
    private KnowledgeBaseMapper knowledgeBaseMapper;

    @Autowired
    private AIModelInitService aiModelInitService;

    @Autowired
    private UserService userService;

    @Autowired
    private VectorStoreManager vectorStoreManager;

    @Override
    public KnowledgeBase createKnowledgeBase(KnowledgeBase knowledgeBase) {
        // 设置创建和更新时�?
        LocalDateTime now = LocalDateTime.now();
        knowledgeBase.setCreateTime(now);
        knowledgeBase.setUpdateTime(now);

        // 保存知识�?
        knowledgeBaseMapper.insert(knowledgeBase);
        
        // 根据知识库创建者获取用户信�?
        User user = null;
        if (knowledgeBase.getCreateUserId() != null) {
            user = userService.getUserById(knowledgeBase.getCreateUserId());
        }
        
        // 生成向量索引名称
        String indexName = "kb_" + knowledgeBase.getId();
        knowledgeBase.setVectorIndexName(indexName);
        
        // 确保向量索引存在
        try {
            // 检查向量存储是否启用
            if (vectorStoreManager.isVectorStoreEnabled()) {
                VectorStore vectorStore = aiModelInitService.getVectorStoreByUser(user, indexName);
                System.out.println("成功为知识库(ID: " + knowledgeBase.getId() + ")创建向量索引: " + indexName);
            } else {
                System.out.println("向量存储功能已禁用，跳过知识库向量索引创建");
            }
        } catch (Exception e) {
            System.err.println("创建向量索引时出错: " + e.getMessage());
            e.printStackTrace();
        }
        
        // 更新知识库的向量索引名称
        knowledgeBaseMapper.updateById(knowledgeBase);
        
        return knowledgeBase;
    }

    @Override
    public KnowledgeBase getKnowledgeBase(Long id) {
        return knowledgeBaseMapper.selectById(id);
    }

    @Override
    public KnowledgeBase updateKnowledgeBase(KnowledgeBase knowledgeBase) {
        // 设置更新时间
        knowledgeBase.setUpdateTime(LocalDateTime.now());

        // 更新知识�?
        knowledgeBaseMapper.updateById(knowledgeBase);
        return knowledgeBase;
    }

    @Override
    public boolean deleteKnowledgeBase(Long id) {
        return knowledgeBaseMapper.deleteById(id) > 0;
    }

    @Override
    public List<KnowledgeBase> getUserKnowledgeBases(Long userId) {
        LambdaQueryWrapper<KnowledgeBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(KnowledgeBase::getCreateUserId, userId)
                .orderByDesc(KnowledgeBase::getCreateTime);
        return knowledgeBaseMapper.selectList(queryWrapper);
    }

    @Override
    public Page<KnowledgeBase> listKnowledgeBases(int page, int size, Long userId) {
        Page<KnowledgeBase> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<KnowledgeBase> queryWrapper = new LambdaQueryWrapper<>();

        // 如果指定了用户ID，则查询该用户的知识�?
        if (userId != null) {
            queryWrapper.eq(KnowledgeBase::getCreateUserId, userId);
        }

        queryWrapper.orderByDesc(KnowledgeBase::getCreateTime);
        return knowledgeBaseMapper.selectPage(pageParam, queryWrapper);
    }
}
